﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Examples
{
    /// <summary>
    /// Executes SQL command via the Camelot WCF Service into a readable ListData object
    /// </summary>
    class WcfServiceExecuteQueryToListData
    {
        public static void DoIt(string connectionStringName, string sharedKey, string sqlCommand, string userName, string password, string domain)
        {
            using (var camelotService = new WcfService.CamelotServiceClient())
            {
                camelotService.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential(userName, password, domain);
                camelotService.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;

                try
                {
                    var xml = camelotService.ExecuteCamelotXml(sqlCommand, connectionStringName, false, sharedKey);
                    var data = Camelot.SharePointIntegration.Client.CamelotXml.ReadXml(xml);

                    if (data.Description != null)
                    {
                        Console.WriteLine("Description");
                        Console.WriteLine("  Id: " + data.Description.ID);
                        Console.WriteLine("  Title: " + data.Description.Title);
                        Console.WriteLine("  Type: " + data.Description.BaseType);
                        Console.WriteLine("  Number of items: " + data.Description.ItemCount);
                        Console.WriteLine("  Created: " + data.Description.Created);
                        Console.WriteLine("  Last modified: " + data.Description.Modified);
                        Console.WriteLine();
                    }

                    if (data.Schema != null)
                    {
                        Console.WriteLine("Columns");

                        foreach (System.Data.DataRow col in data.Schema.Rows)
                            Console.WriteLine("  " + col["DisplayName"] + " (" + col["Type"] + ")");
                    }
                    else
                    {
                        Console.WriteLine("Columns");

                        foreach (System.Data.DataColumn col in data.Rows.Columns)
                            Console.WriteLine("  " + col.ColumnName + " (" + col.DataType.Name + ")");
                    }
                }
                catch (System.ServiceModel.Security.MessageSecurityException e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
    }
}
